package wsz.rocketMq.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import wsz.rocketMq.dao.OrderDao;
import wsz.rocketMq.entity.Order;
import wsz.rocketMq.service.OrderService;
import wsz.rocketMq.util.Constants;

import java.sql.Timestamp;
import java.util.List;

/**
 * 订单业务
 * @author wsz
 * @date 2022/3/2 11:23
 **/
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Override
    public Order findById(Long id) {
        return orderDao.findById(id).orElse(null);
    }

    @Override
    public JSONObject orderPay(Long id) {
        JSONObject result = new JSONObject();
        result.put("status", false);

        Order order = findById(id);
        if (order == null) {
            result.put("msg", "订单获取失败");
            return result;
        }

        if (Constants.PAY_OK.equals(order.getStatus())) {
            result.put("msg", "订单不可重复支付");
            return result;
        }

        // 订单状态变更
        order.setPayTime(new Timestamp(System.currentTimeMillis()));
        order.setStatus(Constants.PAY_OK);
        orderDao.save(order);

        result.put("status", true);
        result.put("msg", "订单已支付");
        return result;
    }

    @Override
    public List<Order> allOrder() {
        return orderDao.findAll(Sort.by(Sort.Order.desc("createTime")));
    }

    @Override
    public Order save(Order entity) {
        return orderDao.save(entity);
    }


}
